package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
	"log"

	pd "zt/go-study/grpc/proto"

	"google.golang.org/grpc"
)

const PORT = "9001"

func main() {
	certFile := "/Users/zhoutao/project/go-study/grpc/conf/client/client.pem"
	keyFile := "/Users/zhoutao/project/go-study/grpc/conf/client/client.key"
	caFile := "/Users/zhoutao/project/go-study/grpc/conf/ca.pem"

	c, err := GetTLSCredentialsByCA(certFile, keyFile, caFile)
	if err != nil {
	    log.Fatalf("GetTLSCredentialsByCA err: %v", err)
	}

	conn, err := grpc.Dial(":"+PORT, grpc.WithTransportCredentials(c))
	if err != nil {
		log.Fatalf("grpc.Dial err: %v", err)
	}
	defer conn.Close()

	client := pd.NewSearchServiceClient(conn)
	resp, err := client.Search(context.Background(), &pd.SearchRequest{Request: "gRPC"})
	if err != nil {
		log.Fatalf("client.Search err: %v", err)
	}

	log.Printf("resp: %s", resp.GetResponse())
}

// GetTLSCredentialsByCA 通过ca获取tls证书
func GetTLSCredentialsByCA(certFile, keyFile, caFile string) (credentials.TransportCredentials, error) {
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		log.Fatalf("tls.LoadX509KeyPair err: %v", err)
	}

	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile(caFile)
	if err != nil {
		log.Fatalf("ioutil.ReadFile err: %v", err)
	}

	if ok := certPool.AppendCertsFromPEM(ca); !ok {
		log.Fatalf("certPool.AppendCertsFromPEM err")
	}

	c := credentials.NewTLS(&tls.Config{
		Certificates: []tls.Certificate{cert},
		ServerName:   "go-grpc",
		RootCAs:      certPool,
	})

	return c, nil
}
